import './public-path'
import Vue from 'vue'
import '@/utils/dayjsPlugs'
import '@/utils/downloadFile'
import layout from '@/utils/layout'

import 'normalize.css/normalize.css' // a modern alternative to CSS resets

import Element from 'element-ui'
import './styles/element-variables.scss'

import '@/styles/index.scss' // global css

import App from './App'
import store from './store'
import router from './router'
import './icons' // icon
import './permission' // permission control
import './utils/error-log' // error log

import * as filters from './filters' // global filters

import globalRegister from './global-register'

import directive from '@/directive' // permission control
Vue.use(layout)
Vue.use(directive)
Vue.use(Element, {
  size: 'small'
})

// register global utility filters
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Vue.config.productionTip = false
let instance = null

function render(props = {}) {
  const { container } = props

  instance = new Vue({
    router,
    store,
    render: (h) => h(App)
  }).$mount(container ? container.querySelector('#app') : '#app')
}

if (!window.__POWERED_BY_QIANKUN__) {
  // 这里是子应用独立运行的环境，实现子应用的登录逻辑

  // 独立运行时，也注册一个名为global的store module
  // globalRegister(store)
  // 模拟登录后，存储用户信息到global module
  // const userInfo = { name: '我是独立运行时名字叫张三' } // 假设登录后取到的用户信息
  // store.commit('global/setGlobalState', { user: userInfo })

  render()
}

export async function bootstrap() {
  console.log('[vue] vue app bootstraped', location.href)
}

export async function mount(props) {
  console.log('[vue] props from main framework', props, store)

  globalRegister(store, props)

  render(props)
}

export async function unmount() {
  instance.$destroy()
  instance.$el.innerHTML = ''
  instance = null
}
